import streamlit as st
import json
from database.queries.product_orm import SynOrmProductQueries
from database.queries.user_orm import SynOrmUserQueries


def __get_default_products():
    with open("default_products.json") as f:
        default_products = json.load(f)
    return default_products

    
def default_products_form(key_base: str="default"):
    if "username" not in st.session_state:
        return
    user = SynOrmUserQueries.get_user_by_username(st.session_state["username"])
    
    default_products: dict = __get_default_products()
    
    
    def insert_toggled_products():
        products_to_insert = []
        for category, products in default_products.items():
            for i in range(len(products)):
                if st.session_state[f"{key_base}_{category}_product_{i}_toggle"]:
                    user_prod_price = st.session_state[
                        f"{key_base}_{category}_product_{i}_price"
                    ]
                    user_prod_max = st.session_state[
                        f"{key_base}_{category}_product_{i}_max"
                    ]
                    
                    changed_product = products[i].copy()
                    changed_product["price_100g"] = user_prod_price
                    changed_product["max_per_day"] = user_prod_max
                    changed_product["username"] = st.session_state["username"]
                    
                    products_to_insert.append(changed_product)
        for product in products_to_insert:
            SynOrmProductQueries.insert_product(**product)


    user_products_names = [p.name for p in user.products]
    
    category_existing_dict = {categ: True for categ in default_products.keys()}
    for category, products in default_products.items():
        for i in range(len(products)):
            if products[i]["name"] in user_products_names:
                st.session_state[
                    f"{key_base}_{category}_product_{i}_toggle"
                ] = False
                continue
            category_existing_dict[category] = False
            
    all_products_exists = True
    for category in category_existing_dict:
        if not category_existing_dict[category]:
            all_products_exists = False
            break
    if all_products_exists:
        return

    with st.expander("➕ Добавление продуктов из списка по умолчанию"):
        with st.form(key=f"{key_base}_default_products_form"):
            for category, products in default_products.items():
                if category_existing_dict[category]:
                    continue
                
                st.markdown(f"**{category}**")
                for i in range(len(products)):
                    if products[i]["name"] in user_products_names:
                        continue
                    with st.container(border=True):
                        col_name, col_price, col_max, col_add = st.columns(4)
                        with col_name:
                            name = products[i]["name"]
                            st.markdown(f"**{name}**")
                        with col_price:
                            st.number_input(
                                label="Цена 100 гр (руб)", 
                                value=float(products[i]["price_100g"]),
                                min_value=0.0,
                                step=0.01,
                                key=f"{key_base}_{category}_product_{i}_price",
                            )
                        with col_max:
                            st.number_input(
                                label="Макс. в день (гр)",
                                min_value=20,
                                value=10000,
                                step=10,
                                key=f"{key_base}_{category}_product_{i}_max",
                            )
                        with col_add:
                            st.checkbox(
                                label="Добавить?", 
                                value=True, 
                                key=f"{key_base}_{category}_product_{i}_toggle",
                            )
            st.form_submit_button(
                label="Добавить продукты", 
                use_container_width=True,
                type="primary",
                on_click=insert_toggled_products,
            )
            